<?php
declare (strict_types=1);

namespace app\command;

use app\data\logic\ProductLogic;
use app\data\model\ProductsCategoryModel;
use app\data\model\ProductsExtCatRelationsModel;
use app\data\model\ProductsModel;
use think\console\Command;
use think\console\Input;
use think\console\Output;
use think\facade\Db;

class SyncExtProCat extends Command
{
    protected function configure()
    {
        // 指令配置
        $this->setName('sync_ext_pro_cat')
            ->setDescription('同步数据库的产品分类默认分配到拓展分类的表');
    }

    protected function execute(Input $input, Output $output)
    {
        $output->writeln('同步分类中...');
        $productsModel = new ProductsModel();
        $productsCatModel = new ProductsCategoryModel();

        $productsModel->where(true)->chunk(10, function ($products) use ($productsCatModel, $output) {

            foreach ($products as $product) {
                $catIds = [];
                if ($product['cate_id'] > 0) {
                    if ($product instanceof ProductsModel) {
                        // 获取产品当前分类
                        $catIds[] = $product['cate_id'];
                        // 获取最底的分类级别
                        $proCat = $productsCatModel->where('id', $product['cate_id'])->field(['id', 'parent_id', 'level'])->find();
                        $parent_id = $proCat['parent_id'];
                        $level = $proCat['level'];
                        // 获取产品level 2 ,1 的分类
                        for ($i = $level - 1; $i > 0; $i--) {
                            $_proCat = $productsCatModel->where('id', $parent_id)->field(['id', 'parent_id'])->find();
                            $catIds[] = $_proCat['id'];
                            $parent_id = $_proCat['parent_id'];
                        }
                        $product->productExtCat()->detach();
                        $result = $product->productExtCat()->attach($catIds);
                        $output->writeln($product['name'].";同步成功！");
                        $output->writeln(json_encode($result,8));
                    }
                }
            }
        });
    }
}
